import { Random } from 'meteor/random';
import { Collections } from '/imports/files/fileCollections';

Template.home_upload_avatar.onCreated(function () {
  this.inUploading = new ReactiveVar(false);
});

Template.home_upload_avatar.onRendered(function () {
  $('#upload-user-img').hover(
    function () {
      $(this).addClass('show');
    },
    function () {
      $(this).removeClass('show');
    }
  );

  $('#crop-user-img-content').croppie({
    viewport: {
      width: 200,
      height: 200,
    },
    boundary: {
      width: 300,
      height: 300
    }
  });
});

Template.home_upload_avatar.helpers({
  inUploading() {
    return Template.instance().inUploading.get();
  }
});

Template.home_upload_avatar.events({
  'click #upload-user-img'() {
    $('#upload-user-img-input').val('').click();
  },
  'change #upload-user-img-input'(event) {
    if (event.target.files && event.target.files[0]) {
      let reader = new FileReader();

      reader.onload = function (e) {
        $('#crop-user-img-content').croppie('bind', {
          url: e.target.result
        });
        $('#crop-user-img-modal').modal();
      };

      reader.readAsDataURL(event.target.files[0]);
    }
  },
  'click #save-new-user-img'(event, instance) {
    $('#crop-user-img-content').croppie('result', {
      type: 'base64',
      format: 'png'
    }).then(function (base64) {
      Collections.Images.insert({
        file: base64,
        isBase64: true,
        fileName: 'user-avatar.png',
        meta: {
          type: 'user-profile-avatar',
          ownerId: Meteor.userId(),
          location: `users/${Meteor.userId()}/profile/`
        },
        onStart() {
          instance.inUploading.set(true);
        },
        onUploaded() {
          instance.inUploading.set(false);
          $('#crop-user-img-modal').modal('hide');
        }
      });
    });
  }
});